//
//  UserCenter.m
//  PalmHospitalTongJi
//
//  Created by leon on 13-11-20.
//  Copyright (c) 2013年 lvxian. All rights reserved.
//

#import "UserCenter.h"
#import "AllNotificationKeys.h"
#import "taskUserManagerService.h"
#import "dataGetUser.h"

@interface UserCenter()

@end

@implementation UserCenter
@synthesize authToken = _authToken;
@synthesize userNo = _userNo;
@synthesize isLogined = _isLogined;
@synthesize user = _user;

+ (instancetype)shareCenter
{
    static UserCenter* center;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        center = [[UserCenter alloc] init];
    });
    return center;
}

- (id)init
{
    if(self = [super init]){
        _user = [self getProfileDisk];
        _authToken = [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_KEY_AUTH];
    }
    return self;
}

- (NSString*)authToken
{
    if(!_authToken){
        _authToken = @"";
    }
    return _authToken;
}


//true:已登录，false:未登录
- (BOOL)isLogined
{
    return _authToken != nil && _authToken.length > 0;
}

#pragma mark - 退出登录

- (void)logout:(void (^)(BOOL suc, NSString* error))completion{
    [DKProgressHUD showLoading];
    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setValue:[UserCenter shareCenter].user.UserId forKeyPath:@"uphone"];
    [dict setValue:[UserCenter shareCenter].user.pid forKeyPath:@"uid"];
    [taskUserManagerService getLoginOut:dict success:^(BaseModel *response, BOOL success) {
        [DKProgressHUD dismiss];
        completion(success,response.message);
    } failture:^(NSError *error, NSString *strDescription) {
         [DKProgressHUD dismiss];
        completion(NO,strDescription);
    }];
}

-(void)clearUserState{
    _user = nil;
    _authToken = nil;

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVE_KEY_AUTH];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:SAVE_KEY_PROFILE];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - user profile info


/**
 *  获取用户信息---调接口
 *
 */
- (void)getProfileRemote:(void (^)(dataGetUserInfo * profile))completitonOK err:(void (^)(NSString * str))completitonFail {

    NSMutableDictionary *dict = [NSMutableDictionary new];
    [dict setField:_userNo value:@"phone"];
    [taskUserManagerService getUser:dict success:^(dataGetUser *response, BOOL success) {
        if (success) {
            self.user = response.data;
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                NSData* userObj = [NSKeyedArchiver archivedDataWithRootObject:self.user];
                if(userObj){
                    [[NSUserDefaults standardUserDefaults] setValue:userObj forKey:SAVE_KEY_PROFILE];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            });
            if (!response.data) {
                [DKProgressHUD showErrorWithStatus:@"获取用户信息失败,请重新登录"];
            }
            completitonOK(self.user);
        }
        
    } failture:^(NSError *error, NSString *strDescription) {
        completitonFail(strDescription);
    }];
}

/**
 *  获取用户信息----取本地数据--
 *
 */
- (dataGetUserInfo *)getProfileDisk
{
    NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:SAVE_KEY_PROFILE];
    if (data) {
        dataGetUserInfo *profile = (dataGetUserInfo *)[NSKeyedUnarchiver unarchiveObjectWithData:data];
        return profile;
    }
    return nil;
}

/**
 *  刷新用户信息本地数据存储
 *
 *  @param completiton <#completiton description#>
 */
- (void)refreshProfiles:(void (^)(dataGetUserInfo * profile))completiton
{
    [self getProfileRemote:^(dataGetUserInfo *profile) {
        self.user = profile;
        completiton(profile);
    } err:^(NSString *str) {
        self.user = nil;
    }];
}

/**
 *  获取用户信息---自动筛选
 *
 */
- (void)getProfiles:(void (^)(dataGetUserInfo * pUser))completiton{
    dataGetUserInfo *profile = [self getProfileDisk];
    if (profile && profile.pid > 0) {
        if(completiton){
            completiton(profile);
        }
    }else{
        
        [self getProfileRemote:^(dataGetUserInfo *profile) {
            if(completiton){
                completiton(profile);
            }
        } err:^(NSString *str) {
            NSLog(@"获取用户信息失败");
        }];
    }
}

@end
